<template>
  <div class="setting-flow">
    <!--S 头部 -->
    <div class="setting-flow-header">
      <el-row class="setting-flow-header-left" type="flex">
        <p class="return-btn" @click="checkModified(goBack, true)">
          <i class="iconfont icon-arrow-left"></i> {{$t('common.base.back')}}
        </p>
        <div>
          <el-row type="flex" style="height: 30px;max-width: 185px;">
            <el-popover placement="bottom" width="224" trigger="click">
              <div class="choose-color-box">
                <div
                  v-for="color in typeColor"
                  :key="color"
                  @click="contractTemplateColor = color"
                  :style="{ background: color }"
                >
                  <i class="el-icon-check" v-if="contractTemplateColor === color"></i>
                </div>
              </div>
              <el-tooltip
                slot="reference"
                effect="dark"
                :content="$t('contract.setting.contractTemplate.modifyContractTemplateColor')"
                placement="bottom"
              >
                <i class="type-color" :style="{ background: contractTemplateColor }"></i>
              </el-tooltip>
            </el-popover>
            <el-tooltip
              effect="dark"
              :content="$t('contract.setting.contractTemplate.modifyContractTemplateName')"
              placement="bottom"
            >
              <el-input
                class="type-name"
                maxlength="100"
                :value="pageName"
                @blur="pageName = formatContractTemplateName(pageName)"
                @input="changeContractTemplateName"
                @focus="pageName = contractTemplateColorName"
                :placeholder="$t('contract.setting.contractTemplate.text3')"
              ></el-input>
            </el-tooltip>
          </el-row>
        </div>
      </el-row>

      <el-row class="setting-flow-header-step" type="flex">
        <div
          v-for="(step, index) in settingStep"
          :key="step.stepName"
          @click="handleClickTab(step)"
          :class="currentTabComponent === step.compName && 'active'"
        >
          <i>{{ index + 1 }}</i>
          <div class="step-name">{{ step.stepName }}</div>
        </div>
      </el-row>

      <div class="setting-flow-header-right">
        <el-button
          class="header-save-btn"
          plain
          @click="submit(true)"
          :loading="pending"
        >{{$t('common.base.save')}}</el-button
        >
      </div>
    </div>
    <!--E 头部 -->
    <component :is="currentTabComponent" :flowData="flowData" ref="comRef" :settingList="settingList" :contractTemplateId="contractTemplateId"></component>
  </div>
</template>

<script>
import _ from 'lodash'
// components
import FlowSettingPanel from './components/FlowSettingPanel';
import ContractAdvanceSetting from '@src/modules/setting/contract/contractSetting/flow/components/ContractAdvanceSetting.vue';

import { getContractTemplateDetail, saveContractTemplate } from '@src/api/ContractApi'

import i18n from '@src/locales'
import { backToFromAccurateTab } from '@src/util/platform'

export default {
  name: 'setting-flow',
  provide() {
    return {
      flowData: this.flowData,
    };
  },
  data() {
    return {
      pageName: i18n.t('contract.setting.moduleName'),
      pending: false,
      flowData: {
        flowConfig: {
          flowSetting: {
            create: {

            },
            audit: {
              approveSetting: {
                level: 0,
                leader: '',
                approvers: []
              }
            },
            close: {
              
            }
          }
        }
      },
      currentTabComponent: 'flow-setting-panel',
      contractTemplateColor: 'rgb(115,127,124)',
      settingList: '',
      contractTemplateColorName: ''
    };
  },
  computed: {
    typeColor() {
      return [
        'rgb(115,127,124)',
        'rgb(38,111,255)',
        'rgb(82,85,255)',
        'rgb(133,82,255)',
        'rgb(188,82,255)',
        'rgb(255,82,212)',
        'rgb(255,149,38)',
        'rgb(110,207,64)',
        'rgb(0,184,213)',
        'rgb(11,161,148)'
      ]
    },
    settingStep() {
      return [
        {
          stepName: this.$t('event.setting.constant.setting_step.name1'),
          compName: 'flow-setting-panel',
        },
        {
          stepName: this.$t('event.setting.constant.setting_step.name2'),
          compName: 'contract-advanc-setting',
        },
      ];
    },
    contractTemplateId() {
      return this.$route.query.id || '';
    }
  },
  methods: {
    // 格式化合同模板名称
    formatContractTemplateName(name) {
      if(name.length > 9) {
        return `${name.slice(0, 9) }...`;
      }

      return name;
    },
    changeContractTemplateName(val) {
      this.pageName = val;
      this.contractTemplateColorName = val;
    },
    goBack() {
      let nowId = window.frameElement.getAttribute('id');
      backToFromAccurateTab(nowId)
    },
    /** 右上角保存按钮 */
    async submit() {
      if(this.pending) return;

      this.pending = true;

      let ret = this.$refs.comRef.submit();

      let params = {
        id: this.contractTemplateId,
        templateName: this.contractTemplateColorName,
        color: this.contractTemplateColor,
        setting: ret.step === '2' ? ret.params : null
      }

      try {
        let res = await saveContractTemplate({...params})

        const { success, message, result } = res || {};

        if (!success) return this.$platform.toast(message, 'error');

        this.$platform.notification({
          title: this.$t('common.base.saveSuccess'),
          type: 'success',
        });

        this.getContractTemplateList()
      } catch (err) {
        console.log('error => 获取合同模板详情', err);
      } finally {
        this.pending = false;
      }
    },
    // 点击当前tab
    handleClickTab({compName}) {
      if(this.currentTabComponent === compName) return;
      this.checkModified(() => {
        this.currentTabComponent = compName;
      });
    },
    /**
     * @description 检查当前tab页是否有修改
     * @param {function} bc 回调函数
     * @param {boolean} isisReturn 是否是返回操作
     */
    async checkModified(bc, isReturn = false) {
      let isModified = false;

      if(this.$refs.comRef.checkModified) {
        isModified = this.$refs.comRef.checkModified();
      }

      let confirmObj = {
        content: isReturn ? this.$t('event.setting.serviceEventTypeSetting.flow.tips1') : this.$t('event.setting.serviceEventTypeSetting.flow.tips2'),
        confirmText: isReturn ? this.$t('common.base.leave') : this.$t('common.base.save'),
        cancelText: isReturn ? this.$t('common.base.cancel') : this.$t('common.base.notSaveForNow')
      }

      if(isModified) {
        this.$confirm(confirmObj.content, '', {
          confirmButtonText: confirmObj.confirmText,
          cancelButtonText: confirmObj.cancelText,
          type: 'warning',
          showClose: false,
          closeOnClickModal: false
        }).then(async () => {
          // 保存
          if(!isReturn) await this.submit();
          bc();
        }).catch(() => {
          // 取消
          if(isReturn) return;
          bc();
        });
      }else {
        bc();
      }
     
    },
    // 获取合同模板详情
    async getContractTemplateList() {
      try {
        let ret = await getContractTemplateDetail({
          id: this.contractTemplateId
        });

        const { success, message, result } = ret || {};

        if (!success) return this.$platform.toast(message, 'error');

        this.contractTemplateColor = result.color;
        this.pageName = result.templateName;
        this.contractTemplateColorName = result.templateName;
        this.settingList = result.setting;
      } catch (err) {
        console.log('error => 获取合同模板详情', err);
      }
    }
  },
  mounted() {
    this.getContractTemplateList()
  },
  components: {
    [FlowSettingPanel.name]: FlowSettingPanel,
    [ContractAdvanceSetting.name]: ContractAdvanceSetting
  },
};
</script>
<style lang="scss" src="./contractFlow.scss" scoped></style>

<style lang="scss" scoped>
  .pageTitle {
    pointer-events: none;
  }
</style>
